/*
 * SMSClient.java
 *
 * Created on May 15, 2008, 2:13 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package morseme;

/**
 *
 * @author tt
 */
import javax.microedition.lcdui.*;
import javax.wireless.messaging.*;
import javax.microedition.io.*;
import java.io.*;
import java.util.*;

public class SMSClient extends Form implements CommandListener, Runnable {

    private static int CALLING = 0;
    private static int OVER = 1;
    private static Command sendCmd = new Command("Send", Command.OK, 1);
    private static Command addCmd = new Command("Add Number",Command.SCREEN,2);
//private static Command addCmd = new Command("Add", Command.OK, 1);
//private static Command addPBCmd = new Command("PhoneBook", Command.OK, 1);
    private static Command cancelCmd = new Command("Cancel", Command.EXIT, 1);
    private TextField addField = new TextField("Number Send : ", "", 15, TextField.PHONENUMBER);
//private TextField numsField = new TextField("Number : ", "N/A", 3000, TextField.ANY);
    private TextField msgField = new TextField("Message : ", "", 500, TextField.ANY);
    private ChoiceGroup numberChoices = new ChoiceGroup("All numbers",Choice.EXCLUSIVE);
    private MessageConnection conn;
    private MainMenu menu;
    private String url,  lnums = "";
    private Vector numbers = new Vector();
    private int state;
    private PhoneBook pBook;

    public SMSClient(MainMenu menu, PhoneBook pBook) {

        super("Text Message");
        this.menu = menu;
        this.pBook = pBook;

        this.state = OVER;
        
//this.addCommand(addCmd);
//this.addCommand(addPBCmd);
        this.addCommand(sendCmd);
        this.addCommand(cancelCmd);
        this.addCommand(addCmd);
        this.setCommandListener(this);

        this.append(addField);
        this.append(numberChoices);
//this.append(numsField);
        this.append(msgField);
    }

    public SMSClient() {

        super("Text Message");

        this.addCommand(sendCmd);
//this.addCommand(addCmd);
        this.addCommand(cancelCmd);
        this.setCommandListener(this);

        this.append(addField);
//this.append(numsField);
        this.append(msgField);
    }

    public void refresh() {
        if (addField != null && msgField != null) {
            addField.setString("");
//numsField.setString("N/A");
            msgField.setString("");
        }
    }

    private String formURL(String telnum) {

        if (telnum.startsWith("0")) {
            telnum = telnum.substring(1);
            telnum = "sms://+66" + telnum + ":" + MorseME.DEFAULT_PORT;
        } else {
            telnum = "sms://+" + telnum + ":" + MorseME.DEFAULT_PORT;
        }

        return telnum;
    }
    
    private String packMessage(String msg){
        String username = (Option.USR_ON == 1) ? Option.USR_STRING : "none";
        String password = (Option.PWD_ON == 1) ? Option.PWD_STRING : "none";
        
        return username+"#"+password+"#"+msg;
    }

    private void sendSMSMessage(Vector numbers, String msg) throws IOException {

        try {
            for (int i = 0; i < numbers.size(); i++) {

                String target = numbers.elementAt(i).toString();
                this.url = this.formURL(target);

                if (conn == null) {
                    conn = (MessageConnection) Connector.open(this.url);
                }
                TextMessage tMsg = (TextMessage) this.conn.newMessage(MessageConnection.TEXT_MESSAGE);
                if (this.url != null) {
                    tMsg.setAddress(this.url);
                    msg = packMessage(msg);
                    tMsg.setPayloadText(msg);
                    conn.send(tMsg);
                    System.out.println("@@1");
                }else{
                    System.out.println("@@2");
                }
                
                conn.close();
                conn = null;
            }

        } catch (IOException ex) {

            ex.printStackTrace();
        } catch (Exception ex) {

            ex.printStackTrace();
        }
    }

    public void addNumber(String[] contact) {

        for (int i = 0; i < contact.length; i++) {

            int idx = contact[i].indexOf(":");
            String number = contact[i].substring(idx + 1, contact[i].length());
            if (number == null || number.equals("")) {
                continue;
            } else {
                numbers.addElement(number);
                lnums += number + ";";
            }
        }
        addField.setString("");
//numsField.setString(lnums);


    }

    public void commandAction(Command c, Displayable d) {

        if (c == sendCmd) {

            numbers.addElement(this.addField.getString());
            if (state == OVER) {
                
                Thread t = new Thread(this);
                t.start();
            }

        } else if (c == cancelCmd) {

            this.url = null;
            lnums = "";
            numbers.removeAllElements();
            numberChoices.deleteAll();
            Display.getDisplay(MorseME.getMIDlet()).setCurrent(this.menu);

        } else if(c == addCmd){
            this.numbers.addElement(this.addField.getString());
            this.numberChoices.append(this.addField.getString(),null);
            this.addField.setString("");
        }

    /*
    else if(c == addCmd){
    String number = addField.getString();
    if(number == null || number.equals("")){
    return;
    }
    if(number.length() > 0){
    numbers.addElement(number);
    }
    addField.setString("");
    lnums += number + ";";
    //numsField.setString(lnums);
    }else if(c == addPBCmd){
    Display.getDisplay(MorseME.getMIDlet()).setCurrent(new NumberList(this, this.pBook));
    }
     */
    }

    public void run() {

        state = CALLING;
        String msgF = msgField.getString();
        
        if (msgF.length() > 0 && numbers.size() > 0) {
            try {
                this.sendSMSMessage(numbers, msgF);

            } catch (IOException ex) {

                state = OVER;
                ex.printStackTrace();
            }
            numbers.removeAllElements();
            numberChoices.deleteAll();
            lnums = "";
            addField.setString("");
            state = OVER;
        }
    }
}

